<?php
namespace App\Libs\wrapper;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Store extends Comm{
    //列表数据
        public function store_list($data){
        $where = "(s.`state`=1 or s.`state`=3) and 1=1";
        //shop_name 店铺名称
        if(isset($data['shop_name'])){
            $where .= " and s.`shop_name` like '%{$data['shop_name']}%'";
        }
        //account 账号
        if(isset($data['account'])){
            $where .= " and s.`account`='{$data['account']}'";
        }
        //platform_id 平台
        if(isset($data['platform_id'])&&$data['platform_id']!=0){
            $where .= " and s.`platform_id` like '%{$data['platform_id']}%'";
        }

        //state 状态：1正常 2停用
        // if(isset($data['state'])&&$data['state']!=0){
        //     $where .= " and s.`state`={$data['state']}";
        // }
        //create_time 创建时间
        if(!empty($data['create_time'])){
            $data['create_time'][1] = $data['create_time'][1] .' 24:00:00';
            $where .= " and s.create_time>='{$data['create_time'][0]}' and s.create_time<='{$data['create_time'][1]}'";
        }
        //分页
        $limit = "";
        if((!empty($data['page'])) and (!empty($data['page_count']))){
            $limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
        }

//	    $sql = "select SQL_CALC_FOUND_ROWS s.*,p.name as platform_name, u.account as user_account, p.mark
//				       from shop s
//				       left join platform p on p.Id = s.platform_id
//				       left join users u on u.Id = s.create_user
//				        where {$where}
//				        order by s.create_time desc {$limit}";


        $sql = "select SQL_CALC_FOUND_ROWS s.*,p.name as platform_name, s.identifying, u.account as user_account, p.mark,p.Id as platform_id,c.name as country_name
				       from shop s
				       left join platform p on p.Id = s.platform_id
				       left join countrys c on c.Id = s.country_id
				       left join users u on u.Id = s.create_user			    
				        where {$where}
				        order by s.create_time desc {$limit}";
        $list = json_decode(json_encode(db::select($sql)),true);
        //总条数
        if(isset($data['page']) and isset($data['page_count'])){
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }
        foreach ($list as $key=>$val){

            // if($val['fba_warehouse_id']!=0){
            //     $cangku =  DB::table('saihe_warehouse')->where('id','=',$val['fba_warehouse_id'])->select('name')->get();
            //     if(!$cangku->isEmpty()){
            //         $list[$key]['fba_name'] = $cangku[0]->name;
            //     }else{
            //         $list[$key]['fba_name'] = '';
            //     }
            // }

            $store_user = $val['store_user'];
            if(!empty($store_user)){

                $store_user = json_decode($val['store_user'],true);
                $user_arr = array();
                $store_users = array();
                $intUser = array();
                if(is_array($store_user)){
                    foreach ($store_user as $storeVal){
                        $intUser[] = intval($storeVal);
                    }
                    $list[$key]['store_user'] = $intUser;
                    if($intUser){
                        $user_account = DB::table('users')->whereIn('Id',$intUser)->select('account')->get();
                        if (!$user_account->isEmpty()){
                            foreach ($user_account as $accountVal){
                                $user_arr[] = $accountVal->account;
                            }
                            $list[$key]['store_user_account'] = implode(",",$user_arr);
                        }
                    }

                }else{
                    $list[$key]['store_user'] = array($store_user);
                    $user_account = DB::table('users')->where('Id','=',$store_user)->select('account')->get();
                    if (!$user_account->isEmpty()){
                        $list[$key]['store_user_account'] = $user_account[0]->account;
                    }
                }
            }else{
                $list[$key]['store_user_account'] = '';
            }

        }


        $return['list']=$list;
        return $return;
    }

    /*
     * 店铺信息获取
     * @parma Id 店铺id
     * */
    public function store_find($data){
        $where = "1=1";
        // Id 店铺id
        if(isset($data['Id'])){
            $where .= " and s.`Id`={$data['Id']}";
        }

        $sql = "select  s.*
				       from shop s
				        where {$where}
				        limit 1";
        $find = json_decode(json_encode(db::select($sql)),true);
        return $find;
    }

    /*
     * 获取lazada平台分类
     */
    public function category_lzd($data)
    {
        $platform_id = $data['platform_id'];
        $sql = "select * from category where pid=0 and platform_id={$platform_id}";
        $category = json_decode(json_encode(db::select($sql)), true);
        $return['list'] = $category;
        //var_dump($return);die;
        return $return;
    }

    //vova平台分类
    public function category_vova($data)
    {
        $platform_id = $data['platform_id'];
        //echo "111";die;
        $sql = "select * from category where pid=0 and platform_id={$platform_id}";
        $category = json_decode(json_encode(db::select($sql)), true);
        $return['list'] = $category;
        return $return;
    }


    /*
     * 新增店铺
     * @pamra platform_id 平台id
     * @param shop_name 店铺名
     * @param account 账号
     * @param description 描述
     * */
    public function store_insert($data){
        $sql = "select `Id`
                    from shop
                    where platform_id={$data['platform_id']} and shop_name='{$data['shop_name']}'
                    limit 1";
        $find = json_decode(json_encode(db::select($sql)),true);
        if(!empty($find)){
            return '该店铺已存在';
        }

        
        // identifying 标识
        if(!empty($data['identifying'])){
            $sql = "select *
            from shop
            where identifying='{$data['identifying']}' 
            limit 1";
            $find = json_decode(json_encode(db::select($sql)),true);
            if(!empty($find)){
                return '该标识已存在';
            }
            $insert['identifying'] = $data['identifying'];
        }
        $insert['platform_id'] = $data['platform_id'];
        $insert['country_id'] = $data['country_id'];
        if($insert['platform_id']==7){
            $country = Db::table('countrys')->select('currency','name')->where('Id',$data['country_id'])->get()->toArray();
//            var_dump($country[0]->name);die;
            if(empty($country[0]->currency)){
                return "新增失败，请在国家管理中添加{$country[0]->name}的国家货币代码";
            }
            $currency_rate = Db::table('huilv')->select('stat','dollar_rate')->where('currency',$country[0]->currency)->orderBy('add_date','desc')->limit(1)->get()->toArray();
            if(empty($currency_rate[0]->dollar_rate)){
                return "新增失败，请在汇率管理中添加{$country[0]->name}的美元汇率";
            }
            if($currency_rate[0]->stat==0){
                return "请联系负责人确认美元汇率是否正确并启用汇率";
            }
//            $app_data['partner_id'] = $data['partner_id'];
            $app_data['shopid'] = $data['shopid'];
//            $app_data['secret'] = $data['secret'];
            $insert['app_data'] = json_encode($app_data);
        }
        $insert['shop_name'] = $data['shop_name'];
        $insert['account'] = $data['account'];
        $insert['description'] = !empty($data['description']) ? $data['description'] : '';
        $insert['create_user'] = $data['user_info']['Id'];
        $insert['store_user'] = json_encode($data['store_user']);
        $insert['create_time'] = date('Y-m-d H:i:s');
        //主营分类
        if(isset($data['main_classification'])){
            $insert['main_classification'] = $data['main_classification'];
        }
        if(isset($data['fba_name'])){
            $fba_id=DB::table('saihe_warehouse')->where('name','=',$data['fba_name'])->select('id')->first();
            if(!empty($fba_id)){
                $id=$fba_id->id;
                $insert['fba_warehouse_id'] = $id;
            }else{
                return '没有找到该赛盒仓库，请确认填写是否正确';
            }
        }

        $add = db::table('shop')->insert($insert);
        if($add){
            return 1;
        }else{
            return '新增失败';
        }
    }

    /*
     * 获取用户
     */
    public function store_user(){
        $user = Db::table('users')->select('Id','account')->where('state',1)->get();

        $return['list']=$user;
        return $return;

    }

    /*
     * 获取国家
     */
    public function store_country(){
        $countyr = Db::table('countrys')->select('Id','name')->where('state',1)->get();

        $return['list']=$countyr;
        return $return;
    }

    /*
     * 获取店铺主营分类
     * */
    public function main_category($data)
    {
        $platform_id = $data['platform_id'];//平台id
        $store_id = $data['store_id'];//店铺id
        $sql = "select * from shop where Id={$store_id}";
        $shop = json_decode(json_encode(db::select($sql)), true);
        if($shop[0]['main_classification']=='all'){
            $category[0]['category_id'] = 'all';
            //var_dump($category);die;
        }elseif(empty($shop[0]['main_classification'])){
            $category = [];
        }else{
            $main_classification = $shop[0]['main_classification'];
            $classification = explode(',',$main_classification);
            $sql = "select * from category 
                where category_id in ({$main_classification}) and platform_id={$platform_id}";
            //var_dump($sql);die;
            $category = json_decode(json_encode(db::select($sql)), true);
            //var_dump($category);die;
        }

        $return['list'] = $category;
        return $return;
    }





    /*
     * 编辑店铺
     * @param Id 店铺id
     * */
    public function store_update($data){
        //var_dump($data);die;
        $set = "";
        // shop_name 店铺名称
        if(!empty($data['shop_name'])){
            $sql = "select *
                    	from shop
                    	where platform_id='{$data['platform_id']}' and shop_name='{$data['shop_name']}' and `Id`!={$data['Id']}
                    	limit 1";
            $find = json_decode(json_encode(db::select($sql)),true);
            if(!empty($find)){
                return '该店铺已存在';
            }

            $set .= ",`shop_name`='{$data['shop_name']}'";
        }

        if(isset($data['platform_id']) && $data['platform_id']==7){
            $country = Db::table('countrys')->select('currency','name')->where('Id',$data['country_id'])->get()->toArray();
//            var_dump($country[0]->name);die;
            if(empty($country[0]->currency)){
                return "新增失败，请在国家管理中添加{$country[0]->name}的国家货币代码";
            }
            $currency_rate = Db::table('huilv')->select('dollar_rate','stat')->where('currency',$country[0]->currency)->get()->toArray();
            if(empty($currency_rate[0]->dollar_rate)){
                return "新增失败，请在汇率管理中添加{$country[0]->name}的美元汇率";
            }
            if($currency_rate[0]->stat==0){
                return "请联系负责人确认美元汇率是否正确并启用汇率";
            }
        }
        // identifying 标识
        if(isset($data['identifying']) && !empty($data['identifying'])){
            $sql = "select *
            from shop
            where identifying='{$data['identifying']}' 
            limit 1";
            $find = json_decode(json_encode(db::select($sql)),true);
            if(!empty($find)){
                return '该标识已存在';
            }
            $set .= ",`identifying`='{$data['identifying']}'";
        }
        // account 账号
        if(isset($data['account']) && !empty($data['account'])){
            $set .= ",`account`='{$data['account']}'";
        }
        // 平台id
        if(isset($data['platform_id']) && !empty($data['platform_id'])){
            $set .= ",`platform_id`='{$data['platform_id']}'";
        }
        // 店铺管理者
        if(isset($data['store_user']) && !empty($data['store_user'])){
            $store_user = json_encode($data['store_user']);
            $set .= ",`store_user`='{$store_user}'";
        }
        // 国家
        if(isset($data['country_id']) && !empty($data['country_id'])){
            $set .= ",`country_id`='{$data['country_id']}'";
        }

        // description 描述
        if(isset($data['description'])){
            $set .= ",`description`='{$data['description']}'";
        }
        //var_dump($data['main_classification']);die;
        // main_classification主营分类
        if(isset($data['main_classification'])){
            $set .= ",`main_classification`='{$data['main_classification']}'";

        }
        // state 状态：1.正常，2.停用
        if(!empty($data['state'])){
            $set .= ",`state`={$data['state']}";
        }
        // authorization_state 授权状态：1.未授权，2.已授权
        if(!empty($data['authorization_state'])){
            $set .= ",`authorization_state`={$data['authorization_state']}";
        }
        // access_token
        if(!empty($data['access_token'])){
            $set .= ",`access_token`='{$data['access_token']}'";
        }
        // app_data 授权参数
        if(!empty($data['app_data'])){
            $set .= ",`app_data`='{$data['app_data']}'";
        }
        if(!empty($data['fba_name'])){
            $fba_id=DB::table('saihe_warehouse')->where('name','=',$data['fba_name'])->select('id')->first();
            if(!empty($fba_id)){
                $id=$fba_id->id;
                $set .= ",`fba_warehouse_id`='{$id}'";
            }else{
                return '没有找到该赛盒仓库，请确认填写是否正确';
            }

        }
//	    var_dump($data['app_data']);die;
        if(empty($set)){
            return '更新数据为空';
        }

        $set = substr($set, 1);
        //var_dump($set);die;
        $sql = "update `shop`
					set {$set}
					where `Id` = {$data['Id']}";
        $update = db::update($sql);
        if($update !== false){
            Redis::Hdel('shop',$data['Id']);
            return 1;
        }else{
            return '操作失败';
        }
    }

    //获取店铺授权跳转地址
    public function store_authorize($data){
        $storeId = $data['store_id'];
        $mark = $data['mark'];
        $sql = "SELECT * 
                    FROM shop s
                    inner join platform p on p.Id=s.platform_id
                    WHERE s.Id = '{$storeId}'";
        $shop = json_decode(json_encode(db::select($sql)),true);
        if(empty($shop)){
            return '平台或店铺不存在';
        }
        // var_dump($shop);die;
        if($mark==2){
            $website = 'https://merchant.wish.com/v3/oauth/authorize?client_id=';

            $appData = $shop[0]['app_data'];
            $appArr = json_decode($appData,true);
            $Client_ID = $appArr['Client_ID'];
            if(!isset($Client_ID)){
                return 'Client_ID为空';
            }
            $website .= $Client_ID;
            $return['website'] = $website;
            return $return['website'];
        }else{
            return '暂未接入授权';
        }
    }

    public function store_category($data){
        echo "11";
    }

//获取平台+店铺
    public function platform_store($data){

        $platform = DB::table('platform')->where('state',1)->get();
        $shop = DB::table('shop')->where('state',1)->select('Id','platform_id','shop_name')->get();
        $platfromArr = array();
        foreach ($platform as $k=>$p){
            $platformArr[$k] = ['id'=>$p->Id,'name'=>$p->name];
        }

        foreach($platformArr as $key=>$val){
            foreach ($shop as $s){
                if($s->platform_id == $val['id']){
                    $platformArr[$key]['children'][] = ['id'=>$s->Id,'name'=>$s->shop_name];
                }
            }
        }

        $return['list']=$platformArr;

        return $return;
    }

}
